package com.dcrzl.gazgmh.common.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Repository;

import java.nio.charset.StandardCharsets;

@Slf4j
@Repository
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

//    @Autowired
//    private OrderService orderService;

    @Value("${spring.data.redis.database}")
    private String redisDataBase;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
        setKeyspaceNotificationsConfigParameter(null);
    }


    /**
     * 监听过期消息
     *
     * @param message key
     * @param pattern 消息事件
     * @return void
     * @author 稻草人之恋
     * @date 2022-09-27 10:17:54
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        // 过期消息key:aaa.......pattern:__keyevent@*__:expired
        log.info("过期消息key:{}.......pattern:{}", expiredKey, new String(pattern, StandardCharsets.UTF_8));
        boolean contains = expiredKey.contains(":" );
        if (contains) {
            String[] split = expiredKey.split(":" );
            String name = split[0];
            String value = split[1];
            if ("cancelOrder".equals(name)) {
                String[] values = value.split("=" );
                String name1 = values[0];
                if ("orderCode".equals(name1)) {
                    String orderCode = values[1];
//                    orderService.cancelOrder(new Order().setOrderCode(orderCode));
                }
            }
        }
    }

    @Override
    protected void doRegister(RedisMessageListenerContainer listenerContainer) {
        listenerContainer.addMessageListener(this, new PatternTopic("__keyevent@"+redisDataBase+"__:expired" ));
    }
}
